var express = require('express');
var router = express.Router();
let { UserModel } = require('../db/index')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 获取会员权益列表
router.get('/vip-benefits', function(req, res) {
  const benefits = [
    {
      id: 1,
      title: '商品全部9折',
      description: '所有商品享受9折优惠',
      icon: '🏷️',
      color: '#4FC3F7',
      isActive: true
    },
    {
      id: 2,
      title: '优先发货',
      description: '订单优先处理发货',
      icon: '🚚',
      color: '#45B7D1',
      isActive: true
    },
  ];

  res.json({
    success: true,
    data: benefits,
    message: '获取会员权益成功'
  });
});

// 获取用户会员状态
router.get('/vip-status', async function(req, res) {
  try {
    // 从请求头或查询参数中获取用户账号
    const userName = req.query.userName || req.headers['user-name'];
    
    if (!userName) {
      return res.json({
        success: false,
        message: '未提供用户账号'
      });
    }

    // 查询用户信息
    const user = await UserModel.findOne({ userName: userName });
    
    if (!user) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }

    // 构造会员状态响应
    const vipStatus = {
      isVip: user.isVip || false,
      level: user.isVip ? 'vip用户' : '普通用户',
      expireDate: user.vipExpireDate || null,
      benefits: user.isVip ? [
        '商品全部9折',
        '优先发货',
      ] : []
    };

    res.json({
      success: true,
      data: vipStatus,
      message: '获取会员状态成功'
    });
  } catch (error) {
    console.error('获取会员状态失败:', error);
    res.json({
      success: false,
      message: '获取会员状态失败'
    });
  }
});

// 激活会员状态 - 支付成功后调用
router.post('/activate-vip', async function(req, res) {
  try {
    const { userName, expireDate } = req.body;
    
    if (!userName) {
      return res.json({
        success: false,
        message: '未提供用户名'
      });
    }

    // 查找并更新用户VIP状态
    const updatedUser = await UserModel.findOneAndUpdate(
      { userName: userName },
      { 
        isVip: true,
        vipExpireDate: expireDate || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] // 默认30天
      },
      { new: true } // 返回更新后的文档
    );

    if (!updatedUser) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: {
        isVip: true,
        level: 'VIP',
        expireDate: updatedUser.vipExpireDate,
        benefits: [
          '商品全部9折',
          '优先发货'
        ]
      },
      message: '会员激活成功'
    });
  } catch (error) {
    console.error('激活会员失败:', error);
    res.json({
      success: false,
      message: '激活会员失败'
    });
  }
});

// 检查商品折扣
router.post('/check-discount', function(req, res) {
  const { productId, originalPrice, userId } = req.body;
  
  // 这里应该检查用户是否为VIP会员
  const isVip = false; // 默认非VIP状态
  
  if (isVip) {
    const discountPrice = originalPrice * 0.9; // 9折优惠
    res.json({
      success: true,
      data: {
        originalPrice: originalPrice,
        discountPrice: discountPrice,
        discount: 0.9,
        isVip: true
      },
      message: 'VIP会员享受9折优惠'
    });
  } else {
    res.json({
      success: true,
      data: {
        originalPrice: originalPrice,
        discountPrice: originalPrice,
        discount: 1,
        isVip: false
      },
      message: '非VIP会员无折扣'
    });
  }
});

module.exports = router;
